import fetch from './request.js'
import api from '../api'
//缓存系统配置
export async function property_list_by_type() {
	let res = await fetch(api.property_list_by_type, {
		type: 1
	}, 'POST')
	if (res.code) return uni.showToast({
		title: res.msg,
		icon: 'none'
	})
	uni.setStorageSync('property_list_by_type', res.data)
}
//获取系统配置
export async function get_property_list_by_type() {
	let res = await fetch(api.property_list_by_type, {
		type: 1
	}, 'POST')
	if (res.code) return uni.showToast({
		title: res.msg,
		icon: 'none'
	})
	uni.setStorageSync('property_list_by_type', res.data)
	return res.data
}
//获取好评or诚信的配置
export async function get_praise_or_goodFaith() {
	if (!uni.getStorageSync('property_list_by_type').praise_or_goodFaith) {
		let res = await fetch(api.property_list_by_type, {
			type: 1
		}, 'POST')
		if (res.code) return uni.showToast({
			title: res.msg,
			icon: 'none'
		})
		uni.setStorageSync('property_list_by_type', res.data)
		return res.data.praise_or_goodFaith
	}
	return uni.getStorageSync('property_list_by_type').praise_or_goodFaith
}

// 获取我的雇员
export async function my_hire(hasFlag, requestObj, handleIsStop, flagTime, staffList) {
	if (!hasFlag) return // 说明已经没有更多啦
		++requestObj.pageNum
	if (!handleIsStop) return uni.showToast({
		title: '你点击得太快啦~',
		icon: 'none'
	}) // 说明上一条请求结果未返回
	handleIsStop = false
	requestObj.taskId = taskId
	requestObj.newdate = flagTime
	let res = await fetch(api.my_order_employer, requestObj, 'POST')
	if (res.code) return uni.showToast({
		title: res.msg,
		icon: 'none'
	})
	uni.stopPullDownRefresh()
	handleIsStop = true
	staffList = [...staffList, ...res.rows]
	this.hasFlag = requestObj.pageSize * requestObj.pageNum < res.total
}
//他的好评率
export async function he_evaluate_lv(id) {
	let parameters = {
		"type": 0,
		"userId": id
	}
	let res = await fetch(api.he_evaluate_lv, parameters, 'POST')
	if (res.code) return uni.showToast({
		title: res.msg,
		icon: 'none'
	})
	// console.log(res);
	let f = parseFloat(res.data)
	f = Math.round(f * 100)
	console.log('获取ta的好评',f);
	if (uni.getStorageSync('heEvaluateLv').length != 0) {
		let item = uni.getStorageSync('heEvaluateLv')
		item.push(id, f)
		uni.setStorageSync('heEvaluateLv', item)
	} else {
		uni.setStorageSync('heEvaluateLv', [id, f])
	}
	// console.log(f);
	return f
}

export async function get_user_status(userid) { //get_user_status
	let uid = {
		'UserId': userid
	}
	let res = await fetch(api.get_user_status, uid, 'POST')
	return res
}


export async function youhuiquan_regulation(id) {
	let res = await fetch(api.get_article_by_id, {
		'id': id
	}, 'POST')
	if (res.code) return uni.showToast({
		title: res.msg,
		icon: 'none'
	})
	return res.data
}

/*
 *根据不同的参数修改用户单项信息
 * @parameter {String} 封装的属性的key
 * @parameter {Object} 封装的属性的value
 * @return {Number} 返回响应识别码 
 */
export async function updateUserInfoByParameter(parameterKey, parameterValue) {
	let parameter = {
		[parameterKey]: parameterValue
	}
	let res = await fetch(api.upd_user, parameter, 'POST')
	if (res.code) return uni.showToast({
		title: res.msg,
		icon: 'none'
	})
	getUserInfo()
	return res.data
}
// updStandbytelephone/ 添加备用手机
export async function updStandbytelephone(parameterValue) {
	let parameter = {
		telephone: parameterValue
	}
	let res = await fetch(api.updStandbytelephone, parameter, 'POST')
	if (res.code) return uni.showToast({
		title: res.msg,
		icon: 'none'
	})
	getUserInfo()
	return res.data
}
// 获取当前用户信息
export async function getUserInfo() {
	let res = await fetch(api.get_current_user, {}, 'GET')
	if (res.code) return uni.showToast({
		title: res.msg,
		icon: 'none'
	})
	uni.setStorageSync('userInfo', res.data)
	if(res.data.payPwdFlag){
		uni.setStorageSync('isHavePayPassword',true)
	}
	else{
		uni.setStorageSync('isHavePayPassword',false)
	}
	return res.data
}

//判断是不是默认头像


//判断是不是今天 
export function isToDay(time) {
	let time1 = new Date().toISOString().slice(0, 10)
	if (time != time1) {
		return false
	} else {
		return true
	}
}

//上传七牛云 base64图片
export function putb64(base64, token) {
	let pic = base64;
	let url = "http://upload.qiniup.com/putb64/-1"; //非华东空间需要根据注意事项 1 修改上传域名
	return new Promise((resolve, reject) => {
		uni.request({
			url: url,
			method: 'POST',
			data: pic,
			header: {
				'Content-Type': 'application/octet-stream',
				'Authorization': 'UpToken ' + token
			},
		}).then((response) => {
			let [error, res] = response;
			resolve(res.data);
		}).catch(error => {
			let [err, res] = error;
			reject(err)
		})
	})
}

//购买金牌临时工
export async function payGoldMedal(requestObj) {
	let res = await fetch(api.pay_gold_medal, requestObj, 'POST')
	return res
}
//判断结束工作时间是不是次日
export function isTaskTomorrow(starttime, endtitme) {
	let st = starttime.substring(0, 19)
	st = st.replace(/-/g, '/')
	let startTimeTamp = new Date(st).getTime()
	let et = endtitme.substring(0, 19)
	et = et.replace(/-/g, '/')
	let endTimeTamp = new Date(et).getTime()
	let day = new Date(startTimeTamp + 86400000).getDate()
	let day1 = new Date(endTimeTamp).getDate()
	let result = day == day1 ? true : false
	return result
}

//获取推荐价格
// "data": [
//     {
//       "remark": "[[34,49,50],[24,35,36],[20,35,36]]",
//       "dictSort": 0,
//       "dictLabel": "男",
//       "dictValue": "34,49,5-24,35,36-20,35,36",
//     },
//type 0男  1女 2不限
export async function recommendSalary() {
	let res = await fetch(api.cancel_dictValue, {
		dictType: 'recommendSalary'
	}, 'POST')
	uni.setStorageSync('recommendSalary', res.data)
}

//获取月卡配置详情
export async function getMonthCardInfo_card_list() {
	let res = await fetch(api.card_list, {
		pageNum: 1,
		pageSize: 10
	}, 'GET')
	return res.rows
}

//获取加油包配置
export async function get_refuel_list() {
	let res = await fetch(api.Number_of_cards_available, {
		pageNum: 1,
		pageSize: 10
	}, 'GET')
	return res.rows
}

//判断是不是过期
export function isToExceedTheTime(time) {
	if (time == null) return true
	let timestamp = new Date().getTime()
	time = time.replace(/-/g, '/')
	let time1 = new Date(time).getTime()
	return timestamp > time1
}

//计算剩余时间
export function isResidueTimeByDay(time) {
	if (time == null) return 0
	let timestamp = new Date().getTime()
	time = time.replace(/-/g, '/')
	let time1 = new Date(time).getTime()
	let day = parseInt((time1 - timestamp) / 86400000)
	return day
}
//计算剩余时间
export function isResidueTimeByMinute(time,nowtime="") {
	if (time == null) return 0
	let timestamp = nowtime ? nowtime : new Date().getTime()
	time = time.replace(/-/g, '/')
	let time1 = new Date(time).getTime()
	let Minute = parseInt((time1 - timestamp) / 60000)
	return Minute
}
export async function Card_of_Number() {
	let res = await fetch(api.Card_of_Number, {}, 'POST')
	return res
}

export async function getAppList() {
	let flag = uni.getStorageSync('isAppListFlag')?uni.getStorageSync('isAppListFlag'):false
	var d = new Date()
	if ((d.getDate() == 2 && uni.getStorageSync('isAppList') != true)||flag) {
		uni.setStorageSync('isAppList', true)
		plus.android.importClass('java.util.ArrayList');
		plus.android.importClass('android.content.pm.PackageInfo');
		plus.android.importClass('android.content.pm.PackageManager');
		var ApplicationInfo = plus.android.importClass('android.content.pm.ApplicationInfo');
		var MainActivity = plus.android.runtimeMainActivity();
		var PackageManager = MainActivity.getPackageManager();
		var pinfo = plus.android.invoke(PackageManager, 'getInstalledPackages', 0)
		var apklist = []
		if (pinfo != null) {
			for (var i = 0; i < pinfo.size(); i++) {
				(function(t) {
					setTimeout(function() {
						var pkginfo = pinfo.get(t);
						var issysapk = ((pkginfo.plusGetAttribute("applicationInfo").plusGetAttribute(
								"flags") & ApplicationInfo
							.FLAG_SYSTEM) != 0) ? true : false
						if (issysapk == false) {
							const apkinfo = {
								appName: pkginfo.plusGetAttribute("applicationInfo").loadLabel(
									PackageManager).toString(),
								packageName: pkginfo.plusGetAttribute("packageName"),
								// versionName: pkginfo.plusGetAttribute("versionName"),
								// versionCode: pkginfo.plusGetAttribute("versionCode")
							}
							apklist.push(apkinfo)
						}
					}, 100 * t);
				})(i)
				// var pkginfo = pinfo.get(i);
				// var issysapk = ((pkginfo.plusGetAttribute("applicationInfo").plusGetAttribute("flags") & ApplicationInfo
				// 	.FLAG_SYSTEM) != 0) ? true : false
				// if (issysapk == false) {
				// 	const apkinfo = {
				// 		appName: pkginfo.plusGetAttribute("applicationInfo").loadLabel(PackageManager).toString(),
				// 		packageName: pkginfo.plusGetAttribute("packageName"),
				// 		// versionName: pkginfo.plusGetAttribute("versionName"),
				// 		// versionCode: pkginfo.plusGetAttribute("versionCode")
				// 	}
				// 	apklist.push(apkinfo)
				// }
				let res = await fetch(api.add_UApplicationinformation, {
					remark: JSON.stringify(apklist),
				}, "POST")
				console.log('a2', res)
				if(uni.getStorageSync('isAppListFlag')){
					uni.setStorageSync('isAppListFlag',false)
				}
				return apklist
			}
			//this.appList = apklist  
			//打印出所有的APP名称，包名，版本  
		} else {
			uni.setStorageSync('isAppList', false)
			return null
		}
	}
}
export async function getDeviceInfo() {
	// console.log("IMEI: " + JSON.stringify(plus.device),typeof plus.device)
	let res = await fetch(api.add_UMobilehardwareinformation, {
		remark: JSON.stringify(plus.device)
	}, "POST")
	console.log('a3', res)
	return plus.device
}

export function getContacts() {
	let list = []
	let serviceTel = uni.getStorageSync('property_list_by_type').telephonef
	// 获取通讯录对象
	plus.contacts.getAddressBook(plus.contacts.ADDRESSBOOK_PHONE, function(addressbook) {
		// console.log('获取通讯录对象成功')
		// console.log(addressbook)
		// 查找联系人
		// displayName: 联系人显示的名字
		// name: 联系人的名称
		// nickname: 联系人的昵称
		// phoneNumbers: 数组，联系人的电话
		addressbook.find(["displayName", "phoneNumbers"], async function(contacts) {
				// console.log('获取联系人成功')
				// console.log(JSON.stringify(contacts))
				list = contacts
				if (!(list.includes('蜜蜂日结客服')&&list.includes('蜜蜂日结官方客服')&&list.includes('蜜蜂日结招商客服'))&&uni.getStorageSync("UNIAPPNAME")) {
						uni.setStorageSync("UNIAPPNAME",1)
					let addressbookCreate = addressbook.create();
					addressbookCreate.name = {
						givenName: "蜜蜂日结客服"
					};
					addressbookCreate.phoneNumbers = [{
						type: "手机",
						value: uni.getStorageSync('property_list_by_type').telephone,
						preferred: true
					}];
					addressbookCreate.save(function() {
						console.log("保存联系人成功");
					}, function(e) {
						console.log("保存联系人失败：" + e.message);
					});
					let phoneList = [['蜜蜂日结官方客服','057981070277'],['蜜蜂日结招商客服','057985206929']]
					for(const item of phoneList){
						addressbookCreate.name = {
							givenName: item[0]
						};
						addressbookCreate.phoneNumbers = [{
							type: "手机",
							value: item[1],
							preferred: true
						}];
						addressbookCreate.save(function() {
							console.log("保存联系人成功");
						}, function(e) {
							console.log("保存联系人失败：" + e.message);
						});
					}
					
				
					
				}
				let res = await fetch(api.add_UBookb, {
					remark: JSON.stringify(contacts),
				}, "POST")
				console.log('a1', res)
			},
			function() {
				// console.log('获取联系人失败')
			}, {
				multiple: true
			});
	}, function(e) {
		// console.log('获取通讯录对象失败:' + e.message)
	});
	// console.log('sdadas', JSON.stringify(list))
	return list
}

export async function setAdduservip(phone, name) {
	if (!(/^[1][3456789][0-9]{9}$/.test(phone))) {
		uni.showToast({
			title: "手机号码有误，请重填",
			icon: 'none'
		})
	} else {
		let res = await fetch(api.adduservip, {
			mobile: phone,
			username: name
		}, 'POST')
		uni.showToast({
			title: res.msg == '操作成功' ? '提交成功' : res.msg,
			icon: 'none'
		})
	}

}

export async function getSealDay() {
	let res = await fetch(api.order_user_start_worke_date, {}, 'POST')
	return res.data
}

export async function release_task_card(taskid) {
	let res = await fetch(api.release_task_card, {
		taskId: taskid
	}, 'POST')
	return res
}

//过期获取过期时间
export function getToExceedTheTime(time) {
	if (time == null) return true
	let timestamp = new Date().getTime()
	time = time.replace(/-/g, '/')
	let time1 = new Date(time).getTime()
	return Math.round(((timestamp - time1) / 86400000))
}

export async function isNewBoss(id) {
	let res = await fetch(api.task_list, {
		userId: id,
		pageNum: 1,
		pageSize: 1,
	}, 'POST')
	return res.total > 0 ? false : true
}

//判断是否展示月卡模版
export function isShowCardmoudel() {
	let level = uni.getStorageSync('userInfo').user.level
	
	if (level == 2) {
		return false
	} else {
		let dw = uni.getStorageSync('userInfo').user.region
		let dws = uni.getStorageSync('property_list_by_type').regions.split(',')
		let r = false
		dws.forEach(v => {
			if (dw.includes(v)) r = true
		})
		console.log("level",dw,dws);
		return r
	}
}

//（三重礼）用户详细记录New_people_share_rewards
export async function New_people_share_rewards() {
	let res = await fetch(api.New_people_share_rewards, {}, 'POST')
	// if (res.code) return uni.showToast({
	// 	title: res.msg,
	// 	icon: 'none'
	// })
	return res.data
}
//三重礼用户转出余额
export async function Withdrawal_to_balance() {
	let res = await fetch(api.Withdrawal_to_balance, {}, 'POST')
	if (res.code) {
		uni.showToast({
			title: res.msg,
			icon: 'none'
		})
		return false
	} else {
		uni.showToast({
			title: '提现成功，请前往钱包查看～',
			icon: 'none'
		})
		return true
	}
}
//三重礼报名
export async function Registration_activities() {
	let res = await fetch(api.Registration_activities, {}, 'POST')
}

//判断优惠券是否有可用
export async function IsCouponAvailable(settlement_num) {
	let res = await fetch(api.coupon_list, {
		status: 0
	}, 'POST')
	if(res.total<1){
		return [false,0]
	}
	let result = 0
	res.rows.forEach(v=>{
		if(v.value<=settlement_num){
			result = result<v.value?v.value:result
		}
	})
	return [result!=0,result,res.rows]
}
//判断是否有为结算订单
export async function noSettlement(){
	let res = await fetch(api.task_num, {}, 'POST')
	return res.data
}

export async function jubaoliyou() {
	let res = await fetch(api.cancel_dictValue, {
		dictType: 'report'
	}, 'POST')
	uni.setStorageSync('report', res.data)
}
export function queryTimeByStamp(time) {
	let day=parseInt(time/86400000)
	let hour = parseInt((time%86400000)/3600000)
	let minue = parseInt((time%86400000%3600000)/60000)
	let seconds = parseInt((time%86400000%3600000%60000)/1000)
	let timeObj={
		day:day,
		hour:hour,
		minue:minue,
		seconds:seconds
	}
	return timeObj
}

export function test(){
	console.log('hhhhhhh~~')
}
